<!--
 * @Author: Sam
 * @Date: 2020-10-22 11:51:41
 * @LastEditTime: 2021-12-02 14:05:12
 * @LastEditors: Sam
 * @Description:
 * @FilePath: \resourcesf:\thework\ygboost-eui\src\components\app\edit\setting\channel\channelEdit.vue
 * @可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <div class="padding-lr-xl">
    <template v-if="isJustShowPrice == 0">
      <el-card>
        <div slot="header" class="clearfix text-left">
          <span class="title-icon">基础配置</span>
        </div>
        <el-form :model="form" ref="basisForm" :rules="rules" size="mini">
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="渠道类型："
                label-width="120px"
                prop="channelType"
              >
                <el-select
                  size="mini"
                  v-model="form.channelType"
                  placeholder="请选择渠道类型"
                >
                  <el-option
                    v-for="item in channelTypeList"
                    :key="item.value"
                    :label="item.type"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="渠道代码：" label-width="120px" prop="code">
                <el-input size="mini" v-model="form.code"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="最小单箱计费重："
                label-width="120px"
                prop="minChargeWeight"
              >
                <el-input size="mini" v-model="form.minChargeWeight"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="平均到货时间：" label-width="120px">
                <el-input size="mini" v-model="form.arriveTime"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="渠道名称：" label-width="120px" prop="name">
                <el-input size="mini" v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态：" label-width="120px" prop="status">
                <el-select
                  size="mini"
                  v-model="form.status"
                  placeholder="请选择状态"
                >
                  <el-option label="启用" value="1"></el-option>
                  <el-option label="关闭" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="最小运单计费量："
                label-width="120px"
                prop="minChargeCount"
              >
                <el-input size="mini" v-model="form.minChargeCount"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="渠道说明：" label-width="120px">
                <!-- <el-input size="mini" v-model="form.channelExplain"></el-input> -->
                <span @click="showTinymce = true">查看编辑</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="体积重规则："
                label-width="120px"
                prop="bulkfactorRule"
              >
                <el-select
                  size="mini"
                  v-model="form.bulkfactorRule"
                  placeholder="请选择体积重规则"
                >
                  <el-option
                    v-for="(label, value) in volumeWightRules"
                    :key="label"
                    :label="value"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="推送服务商："
                label-width="120px"
                prop="pushService"
              >
                <el-input type="text" v-model="form.pushService" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="下家渠道ID"
                label-width="120px"
                prop="serviceChannelId"
              >
                <el-input type="text" v-model="form.serviceChannelId" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="token" label-width="120px" prop="token">
                <el-input type="text" v-model="form.token" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="体积规则："
                label-width="120px"
                prop="volumeRule"
              >
                <el-input size="mini" v-model.trim="form.volumeRule"></el-input>
                <span style="color: #f63939; font-size: 10px"
                  >按体积计费，实重/该值，取大值</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="所属航线："
                label-width="120px"
                prop="isRoute"
              >
                <el-select
                  size="mini"
                  v-model="form.isRoute"
                  placeholder="请选择所属航线"
                >
                  <el-option
                    v-for="(label, value) in routeList"
                    :key="value"
                    :label="label"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item
                label="API地址"
                label-width="120px"
                prop="requestAddress"
              >
                <el-input type="text" v-model="form.requestAddress" />
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item
                label="下家渠道编码"
                label-width="120px"
                prop="serviceChannelCode"
              >
                <el-input type="text" v-model="form.serviceChannelCode" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="投保率："
                label-width="120px"
                prop="insureRate"
              >
                <el-input size="mini" v-model.trim="form.insureRate"></el-input>
                <span style="color: #f63939; font-size: 10px"
                  >默认投保率为0.0009,卡铁投保率为0.00022</span
                >
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="客户端是否显示："
                label-width="120px"
                prop="showClient"
              >
                <el-select
                  size="mini"
                  v-model="form.showClient"
                  placeholder="请选择"
                >
                  <el-option label="显示" :value="1"></el-option>
                  <el-option label="不显示" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item
            label="渠道能力："
            label-width="120px"
            prop="channelAbility1"
          >
            <el-checkbox-group size="mini" v-model="form.channelAbility1">
              <el-checkbox
                v-for="item in channelAbilitys"
                :key="item.id"
                :label="`${item.id}`"
                name="channelAbility"
              >
                {{ item.category }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            label="特殊产品："
            label-width="120px"
            prop="specialProduct1"
          >
            <el-checkbox-group size="mini" v-model="form.specialProduct1">
              <el-checkbox
                v-for="item in specialProducts"
                :key="item.id"
                :label="`${item.id}`"
                name="specialProduct"
              >
                {{ item.category }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item
                label="是否包税："
                label-width="120px"
                prop="other1"
              >
                <el-checkbox-group size="mini" v-model="form.other1">
                  <el-checkbox label="32" name="other2">是</el-checkbox>
                  <el-checkbox label="38" name="other2">否</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="交货条款："
                label-width="120px"
                prop="other2"
              >
                <el-checkbox-group size="mini" v-model="form.other2">
                  <el-checkbox label="29" name="other3">DDP</el-checkbox>
                  <el-checkbox label="28" name="other3">DDU</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </template>

    <el-card class="margin-top">
      <div slot="header" class="clearfix text-left">
        <span class="title-icon">价格表</span>
      </div>
      <el-tabs
        type="border-card"
        v-model="timeActiveName"
        v-if="tableInfo && tableInfo.channelUseTimes"
        @tab-click="handleUserTimeClick"
      >
        <el-tab-pane
          v-for="relateIterm in tableInfo.channelUseTimes"
          :key="relateIterm.id"
          :label="relateIterm.time"
          :name="`${relateIterm.id}`"
        >
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            v-if="tableInfo && tableInfo.channelSubareas"
          >
            <el-tab-pane
              v-for="item in tableInfo.channelLoadingPorts"
              :key="item.id"
              :label="`${loadPortAddress[item.consignmentPlaceId]} +${
                item.price
              }`"
              :name="`${item.consignmentPlaceId}`"
            >
              <TableComponent
                v-if="activeName == item.consignmentPlaceId"
                :status="`t${item.id}`"
                :tableColumns="tableInfo.channelChargingSections"
                :tableData="tableInfo.channelSubareas"
                :channelFormulaMap="tableInfo.channelFormulaMap"
                :sortList="sortList"
                :countrys="initCustomerChannelData.countrys"
                :countryStates="initCustomerChannelData.countryStates"
              />
            </el-tab-pane>
          </el-tabs>
          <div v-else>暂无价格</div>
        </el-tab-pane>
      </el-tabs>
      <div v-else>暂无价格</div>

      <!--<el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        v-if="tableInfo && tableInfo.channelSubareas"
      >
        <el-tab-pane
          v-for="item in tableInfo.channelLoadingPorts"
          :key="item.id"
          :label="`${loadPortAddress[item.consignmentPlaceId]} +${item.price}`"
          :name="`${item.consignmentPlaceId}`"
        >
          <TableComponent
            v-if="activeName == item.consignmentPlaceId"
            :status="`t${item.id}`"
            :tableColumns="tableInfo.channelChargingSections"
            :tableData="tableInfo.channelSubareas"
            :channelFormulaMap="tableInfo.channelFormulaMap"
            :sortList="sortList"
            :countrys="initCustomerChannelData.countrys"
            :countryStates="initCustomerChannelData.countryStates"
          />
        </el-tab-pane>
      </el-tabs>

      <div v-else>暂无价格</div>-->
    </el-card>

    <el-dialog
      title="渠道说明"
      :visible.sync="showTinymce"
      width="50%"
      :modal="false"
    >
      <tinymce v-model="form.channelExplain" :height="500" />
    </el-dialog>
  </div>
</template>

<script>
import { m } from "@/store/yg/common/local";
import { ajax } from "@/store/yg/common/utils";
import { clone } from "@/utils/clone";
import TableComponent from "./TableComponent";
const Tinymce = () => import("@/components/app/components/Tinymce");
export default {
  components: {
    TableComponent,
    Tinymce,
  },
  data() {
    return {
      showTinymce: false,
      isJustShowPrice: 0,
      defaultProps: {
        children: "children",
        label: "label",
      },
      sortList: [],
      activeName: "",
      timeActiveName: "",
      form: {
        channelType: "",
        status: "",
        name: "",
        code: "",
        arriveTime: "",
        channelExplain: "",
        minChargeCount: "",
        minChargeWeight: "",
        bulkfactorRule: "6000",
        isRoute: "",
        channelAbility1: [],
        specialProduct1: [],
        other1: [],
        other2: [],
        channelAbility: [],
        specialProduct: [],
        other: [],
        pushService: "",
        serviceChannelId: "",
        requestAddress: "",
        token: "",
        serviceChannelCode: "",
        volumeRule: "",
        insureRate: "",
        showClient: 1,
      },
      initCustomerChannelData: [],
      channelAbilitys: [],
      channelTypeList: [],
      routeList: [],
      others: [],
      specialProducts: [],
      volumeWightRules: [],
      loadPortAddress: [],
      countrys: [],
      countryStates: [],
      rules: {
        minChargeCount: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "须为数字,可留3位小数",
          },
        ],
        minChargeWeight: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "须为数字,可留3位小数",
          },
        ],
        channelType: [
          { required: true, message: "请选择渠道类型", trigger: "change" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        name: [{ required: true, message: "请填写渠道名称", trigger: "blur" }],
        code: [{ required: true, message: "请选择渠道代码", trigger: "blur" }],
        bulkfactorRule: [
          { required: true, message: "请选择体积重规则", trigger: "change" },
        ],

        channelAbility1: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        specialProduct1: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        other1: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        other2: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        minChargeCount: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "须为数字,可留3位小数",
          },
        ],
        minChargeWeight: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,3})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "须为数字,可留3位小数",
          },
        ],
      },
      tableInfo: null,
    };
  },
  computed: {},
  props: ["field", "customerChannelId", "justShowPrice"],
  mounted() {
    console.log("this.$store.state.edit", this.$store.state.edit);
    console.log("this.$store.state.edit.row", this.$store.state.edit.row);
    if (this.justShowPrice) {
      this.isJustShowPrice = this.justShowPrice;
    }
    this.init();
    // 存在即是编辑
    if (this.$store.state.edit.row.channelType) {
      const form = this.$store.state.edit.row;
      this.form.id = this.$store.state.edit.row.id;
      console.log(
        "%cthis.form.id: ",
        "color: MidnightBlue; background: Aquamarine;",
        this.form.id
      );

      if (form.other) {
        const other = form.other.split(",");
        this.form.other1 = other.filter((x) => x === "32" || x === "38");
        this.form.other2 = other.filter((x) => x === "29" || x === "28");
      }

      if (form.channelAbility) {
        this.form.channelAbility1 = form.channelAbility.split(",");
      }

      this.form.specialProduct1 = form.specialProduct
        ? form.specialProduct.split(",")
        : ["53"];

      this.form.channelType = form.channelType;
      this.form.status = form.status.toString();
      this.form.name = form.name;
      this.form.code = form.code;
      this.form.arriveTime = form.arriveTime;
      this.form.channelExplain = form.channelExplain;
      this.form.minChargeCount = form.minChargeCount;
      this.form.minChargeWeight = form.minChargeWeight;
      this.form.bulkfactorRule = form.bulkfactorRule;
      this.form.isRoute = form.isRoute;

      this.form.channelAbility = form.channelAbility;
      this.form.specialProduct = form.specialProduct;
      this.form.pushService = form.pushService;
      this.form.serviceChannelId = form.serviceChannelId;
      this.form.serviceChannelCode = form.serviceChannelCode;
      this.form.other = form.other;
      this.form.requestAddress = form.requestAddress;
      this.form.token = form.token;
      this.form.showClient = form.showClient;
      if (form.volumeRule) {
        this.form.volumeRule = form.volumeRule;
      }
      this.form.insureRate = form.insureRate;
    }
  },
  watch: {
    customerChannelId: {
      handler(nVal) {
        this.init();
      },
    },
  },
  destroyed() {
    console.log("1111111111 :>> ", 1111111111);
    this.form = {
      channelType: "",
      status: "",
      name: "",
      code: "",
      arriveTime: "",
      channelExplain: "",
      minChargeCount: "",
      minChargeWeight: "",
      bulkfactorRule: "",
      isRoute: "",
      channelAbility1: [],
      specialProduct1: [],
      other1: [],
      other2: [],
      channelAbility: [],
      specialProduct: [],
      other: [],
      pushService: "",
      serviceChannelId: "",
      requestAddress: "",
      token: "",
      volumeRule: null,
      insureRate: "",
    };
  },
  methods: {
    async init() {
      // let initCustomerChannelData = localStorage.getItem(
      //   "initCustomerChannelData"
      // );
      // if (initCustomerChannelData && initCustomerChannelData !== "null") {
      //   initCustomerChannelData = JSON.parse(initCustomerChannelData);
      // } else {
      const attrs = {
        class: "com.tofba.app.client.seaair.CustomerChannelClient",
      };
      this.initCustomerChannelData = await ajax(
        "initCustomerChannelData",
        {},
        attrs
      );

      //   localStorage.removeItem("initCustomerChannelData");
      //   localStorage.setItem(
      //     "initCustomerChannelData",
      //     JSON.stringify(initCustomerChannelData)
      //   );
      // }
      this.channelAbilitys = this.initCustomerChannelData.channelAbilitys;
      this.channelTypeList = this.initCustomerChannelData.channelTypeList;
      this.others = this.initCustomerChannelData.others;
      this.specialProducts = this.initCustomerChannelData.specialProducts;
      this.volumeWightRules = this.initCustomerChannelData.volumeWightRules;
      this.routeList = this.initCustomerChannelData.routeList;
      this.loadPortAddress = this.initCustomerChannelData.loadPortAddress;
      this.countrys = this.initCustomerChannelData.countrys;
      this.countryStates = this.initCustomerChannelData.countryStates;
      let channelId = this.$store.state.edit.row.id;
      if (!channelId && this.customerChannelId) {
        channelId = this.customerChannelId;
      }
      ajax(
        "queryChannelById",
        {
          customerChannelId: channelId,
          consignmentPlaceId: null,
        },
        attrs
      )
        .then((res) => {
          this.tableInfo = res;

          if (
            res.relateId &&
            res.customerChannel.channelSubareaIds[res.relateId]
          ) {
            this.sortList = res.customerChannel.channelSubareaIds[res.relateId];
          }
          if (res && res.channelUseTimes && res.channelUseTimes.length > 0) {
            this.timeActiveName = res.channelUseTimes[0].id.toString();
          }

          if (
            res &&
            res.channelLoadingPorts &&
            res.channelLoadingPorts.length > 0
          ) {
            this.activeName =
              res.channelLoadingPorts[0].consignmentPlaceId.toString();
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    m(k) {
      return m(k);
    },
    callbefore() {
      this.$store.state.edit.row = this.form;
      console.log("submit", this.$store.state.edit.row);
    },
    callvalidate() {
      this.$refs.basisForm.validate((valid) => {
        if (valid) {
          console.log("submit");
          const cloneData = clone(this.form);
          this.form.channelAbility = cloneData.channelAbility1.toString();
          this.form.specialProduct = cloneData.specialProduct1.toString();
          this.form.other = [
            ...cloneData.other1,
            ...cloneData.other2,
          ].toString();
        } else {
          console.log("error submit!!");
          this.form.channelAbility = [];
          this.form.specialProduct = [];
          this.form.other = [];
          return false;
        }
      });

      return true;
    },
    handleUserTimeClick(tab) {
      console.log("activeName", tab.name);
      let channelId = this.$store.state.edit.row.id;
      if (!channelId && this.customerChannelId) {
        channelId = this.customerChannelId;
      }
      const attrs = {
        class: "com.tofba.app.client.seaair.CustomerChannelClient",
      };
      ajax(
        "queryChannelById",
        {
          customerChannelId: channelId,
          relateId: parseInt(tab.name),
        },
        attrs
      )
        .then((res) => {
          //console.log("res",JSON.stringify(res));
          this.tableInfo = res;
          if (
            res &&
            res.channelLoadingPorts &&
            res.channelLoadingPorts.length > 0
          ) {
            this.activeName =
              res.channelLoadingPorts[0].consignmentPlaceId.toString();
          }
          if (
            res.relateId &&
            res.customerChannel.channelSubareaIds[res.relateId]
          ) {
            this.sortList = res.customerChannel.channelSubareaIds[res.relateId];
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleClick(tab) {
      console.log(this.timeActiveName);
      console.log("activeName", this.activeName, tab.name);
      let channelId = this.$store.state.edit.row.id;
      if (!channelId && this.customerChannelId) {
        channelId = this.customerChannelId;
      }
      const attrs = {
        class: "com.tofba.app.client.seaair.CustomerChannelClient",
      };
      ajax(
        "queryChannelById",
        {
          customerChannelId: channelId,
          consignmentPlaceId: parseInt(tab.name),
          relateId: parseInt(this.timeActiveName),
        },
        attrs
      )
        .then((res) => {
          //console.log("res",JSON.stringify(res));
          this.tableInfo = res;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleNodeClick(data) {
      console.log(data);
    },
  },
};
</script>

<style scoped>
/deep/.el-select {
  width: 100%;
}
.padding-lr-xl >>> .el-dialog__header {
  text-align: left;
}
</style>
